package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 融创
 */
@Component
@Slf4j
@ProductType(ProductChannelConstant.RONG_CHANG)
public class RongChuangReport extends AbstractProductReport {
    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {

        String reportUrl = ocpxAccountDTO.getReportUrl();
        Map<String, String> stringStringMap = HttpUtil.decodeParamMap(reportUrl, StandardCharsets.UTF_8);

        String channel=stringStringMap.get("channel");
        String packId=stringStringMap.get("packId");

        String time=String.valueOf(System.currentTimeMillis());
        String token=SecureUtil.md5(channel+ocpxAccountDTO.getProductKey()+time);

        Map<String,Object> params=new HashMap<>();
        params.put("requestId", reportDTO.getBizRequestId());
        params.put("imei", reportDTO.getImei());
        params.put("oaid",reportDTO.getOaid());
        params.put("idfa",reportDTO.getIdfa());
        params.put("imeiMd5",reportDTO.getImeiSum());
        params.put("oaidMd5",reportDTO.getOaidSum());
        params.put("idfaMd5",reportDTO.getIdfaSum());
        params.put("androidId",reportDTO.getHash_android_id());
        params.put("caid",reportDTO.getCaid());
        params.put("clientIp",reportDTO.getIp());
        params.put("userAgent",reportDTO.getUser_agent());
        params.put("time", time);
        params.put("token",token);
        params.put("reportType",1);

        String allCallbackUrl = String.format(productConfigDTO.getCallbackUrl(), reportDTO.getBizRequestId());
        params.put("callback",allCallbackUrl);

        String urlParams = UrlUtil.covertParamsOrderByAsc(params);
        String finalUrl = ocpxAccountDTO.getReportUrl() + "&" + urlParams;
        log.info("账号为{},请求产品端的完整地址为 {}", ocpxAccountDTO.getId(), finalUrl);
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 请求产品端，响应的结果为{}", ocpxAccountDTO.getId(), body);
        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }
}
